//
//  ThemeManager.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2024/12/25.
//

import SwiftUI

var commonManager = CommonManager()
//常用的
class CommonManager: ObservableObject {
    //来电
    @Published var isVoiceCall = false
    @Published var isVoiceWait = false
    @Published var isBackground = false //是否处于后台
    var callParam : VoiceCallParam = VoiceCallParam()
    //来信动画
    @Published var isWeeklyLetter = false
    //来信打开
    @Published var isWeeklyLetterOpen = false
    //来信是否自动打开
    @Published var isWeeklyLetterOpenAuto = false
    var weeklyLetterRole : AiRoleBean = AiRoleBean()
    var weeklyLetterBean : WeeklyLetterBean = WeeklyLetterBean()
    private var countdownLetterTask: Task<Void, Never>? //来信倒计时
    
    func showVoiceCall(_ bean: VoiceCallParam) {
        withAnimation {
            callParam = bean
            hideVoiceWait()
            isVoiceCall = true
        }
    }
    
    func showVoiceWaitDialog(_ bean: VoiceCallParam) {
        withAnimation {
            callParam = bean
            isVoiceWait = true
        }
    }
    
    func hideVoiceCall() {
        withAnimation {
            isVoiceCall = false
        }
    }
    
    func hideVoiceWait() {
        withAnimation {
            isVoiceWait = false
        }
    }
    
    func showWeeklyLetter(_ bean: AiRoleBean) {
        withAnimation {
            weeklyLetterRole = bean
            isWeeklyLetter = true
        }
        // 启动倒计时任务
        countdownLetterTask = Task {
            try? await Task.sleep(nanoseconds: 10 * 1_000_000_000) // 10 秒
            if isWeeklyLetter {
                hideWeeklyLetter()
            }
        }
    }
    
    func showWeeklyLetterOpen(_ isAuto:Bool, _ bean: WeeklyLetterBean) {
        withAnimation {
            do {
                //避免引用
                weeklyLetterBean = try fromJson(toJson(bean), WeeklyLetterBean.self) ?? bean
            } catch {
                weeklyLetterBean = bean
            }
            isWeeklyLetterOpen = true
            isWeeklyLetterOpenAuto = isAuto
        }
    }
    
    func hideWeeklyLetter() {
        // 取消倒计时任务
        countdownLetterTask?.cancel()
        DispatchQueue.main.async {
            withAnimation {
                self.isWeeklyLetter = false
            }
        }
    }
    
    func hideWeeklyLetterOpen() {
        DispatchQueue.main.async {
            withAnimation {
                self.isWeeklyLetterOpen = false
            }
        }
    }
    
}
